package sliding_window;

import java.util.HashMap;
import java.util.Map;

public class Solution {

    public static String maxUnRepeatedSubstrings(String s) {
        if (s == null || s.isEmpty()) {
            return "";
        }
        Map<Character, Integer> map = new HashMap<>();
        int maxLen = 0;
        int maxStart = 0;
        int start = 0;
        for (int end = 0; end < s.length(); end++) {
            char c = s.charAt(end);
            if (map.containsKey(c) && map.get(c) >= start) {
                start = map.get(c) + 1;
            }
            map.put(c, end);
            int currentLen = end - start + 1;
            if (currentLen > maxLen) {
                maxLen = currentLen;
                maxStart = start;
            }
        }
        return s.substring(maxStart, maxStart + maxLen);
    }

    /**
     * 最长不重复字符串代输出
     * in: abcdeefg
     * out: abcde
     * 这道题用Java如何解决？
     */
    public static void main(String[] args) {
        String input = "abcdeefg";
        System.out.println("Output: " + maxUnRepeatedSubstrings(input));
        input = "abcadef";
        System.out.println("Output: " + maxUnRepeatedSubstrings(input));
    }
}
